<!--
* description: 备件销售收款 - 收款
* author: xiaochengzuan
* createdDate: 2021-2-23
-->
<template>
  <section class="editBigAreaInfo">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :title="textMap[popupsState]"
      :append-to-body="true"
      :visible.sync="curPopupsVisible"
      width="70%"
      @close="closeEdit"
      @opened="openDialog"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />
      <div class="filter-container filter-params">
        <el-row ref="vailComponentList" :gutter="26">          
          <one-table-template
          :key="shuaxin"
          ref="multipleTable"
          :dynamic-buttons="tableButtons"
          :dynamic-components="tableComponents"
          :dynamic-table-cols="tableCols"
          :dynamic-is-show-select="false"
          :dynamic-is-show-more-btn="true"
          :dynamic-is-init-table="true"
          :dynamic-table-defult-height="300"
          :callback-obj="callbackObj"
          :isshow-search-table-button="false"
          :dynamic-api-config="apiConfig"
          :dynamic-form-fields="formField"          
        />
        </el-row>
      </div>
      <el-dialog
          v-dialogDrag
          :visible="showCodediv"
          center
          width="30%"
          :append-to-body="true"
          :close-on-click-modal="false"
          @close="closeCode"
        >
          <dialogHeader slot="title" title="收款信息" :style-type="$store.state.app.dialogType" />
          <div
          style="margin-left:0 auto;padding-bottom:32px;"
            id="qrcode"
            ref="qrcode"
          />
      </el-dialog>
    </el-dialog>
  </section>
</template>
<script>
import { formMixins } from '@/components/mixins/formMixins'
import { orgApis } from '@/api/pa/salesManagementOfSparePartsInOutlets'
import OneTableTemplate from '@/components/templates/oneTable'
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import QRCode from 'qrcodejs2'

export default {
  components: {
    OneTableTemplate,
    dialogHeader: () => import('@/components/dialogHeader')
  },

  // 组件混入对象
  mixins: [formMixins, oneTableWithViewTemplateMixins],

  props: {
    popupsVisible: { type: Boolean, default: false },
    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: { type: Object, default: function() { return {} } }
  },
  mounted(){
    this.$nextTick(() => {
      this.queryTableaaa()
    })
  },
  data() {
    // const viewPageCode = 'bigAreaInfo-edit'
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      showCodediv:false,
      shuaxin: '',
      QRcode:{},
      // 保存API配置对象
      apiConfig: orgApis.queryOrderSheetReceive,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          icon: 'iconfont  icon-preservation',
          clickEvent: () => {this.formField.payType === '1' ?this.showCode() : this.save()},
          text: '收款' /* 保存*/,
          position: 'right'
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          icon: 'iconfont  icon-cancel',
          clickEvent: () => this.closeEdit(),
          text: this.$t('sys.button.cancel') // 取消
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey6',
              codeField: 'payType',
              labelName: '支付方式：',
              component: () => import('@/components/org/radioBox/index.vue'),
              type: 'radio',
              isMust: true,
              span: 24,
              options: [
                { value: '1', label: 'POS支付' },
                { value: '2', label: '现金支付' }
              ]
            },
            {
              compKey: 'compKey1',
              labelName: '销售单号：',
              codeField: 'saleOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              isMust: true,
              span: 8,
              disabled: true
            },
            // {
            //   compKey: 'compKey2',
            //   labelName: '结算方式：',
            //   codeField: 'paymentMethod',
            //   parentFileds: "show:payType-1-2",
            //   component: () => import('@/components/org/LookupValue'),
            //   oFields: 'statusId,statusText',
            //   options: [
            //     { statusId: '0', statusText: '银行' },
            //     { statusId: '1', statusText: '现金' },
            //     { statusId: '2', statusText: '电子支付' }
            //   ],
            //   type: 'dropdownList',
            //   isRequire: true,
            //   isMust: true,
            //   isShow:false,
            //   span: 8
            // },
            {
              compKey: 'compKey3',
              labelName: '收款金额：',
              codeField: 'paymentAmount',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isShow:false,
              isRequire: true,
              validrule: {
                // 保留一到两位小数
                isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
                resectMessage: {
                  isformat: '请输入正确的金额!'
                }
              },
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey4',
              labelName: '票据类型：',
              codeField: 'invoiceType',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              isShow:false,
              options: [
                // { statusId: '0', statusText: '机构车发票' },
                { statusId: '007', statusText: '普通发票' },
                { statusId: '026', statusText: '增值税发票' },
                // { statusId: '3', statusText: '收据' }
              ],
              type: 'dropdownList',
              isRequire: true,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey5',
              labelName: '票据金额：',
              codeField: 'invoiceAmount',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              isRequire: true,
              disabled:true,
              isShow:false,
              validrule: {
                // 保留一到两位小数
                isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
                resectMessage: {
                  isformat: '请输入正确的金额!'
                }
              },
              span: 8
            },
            {
              compKey: 'compKey7',
              labelName: '已收尾款',
              codeField: 'actualAmount' ,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              disabled:true,
              validrule: {
                // 保留一到两位小数
                isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
                resectMessage: {
                  isformat: '请输入正确的金额!'
                }
              },
              span: 8
            },
            {
              compKey: 'compKey8',
              labelName: '应收尾款',
              codeField: 'notReceivableAmount',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              disabled:true,
              validrule: {
                // 保留一到两位小数
                isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
                resectMessage: {
                  isformat: '请输入正确的金额!'
                }
              },
              span: 8
            },
            {
              compKey: 'compKey8',
              labelName: '应收总价',
              codeField: 'receivableAmount',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              disabled:true,
              validrule: {
                // 保留一到两位小数
                isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
                resectMessage: {
                  isformat: '请输入正确的金额!'
                }
              },
              span: 8
            }        
          ],
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'gatheringProject',
              label: '收款项目',
              width: null,
              isMul: false,
              align: 'center',
              hidden:false
            },
            {
              prop: 'transactionSerialCode',
              label: '交易流水号', 
              width: 260,
              hidden:false
            },
            {
              prop: 'receiptNumberCode',
              label: '销售单号', width: 180
            },
            {
              prop: 'payName',
              label: '付款人', width: 120
            },
            {
              prop: 'payTime',
              label: '支付时间', width: 180
            },
            {
              prop: 'yMoney',
              label: '应收金额',
              width: 100
            },
            {
              prop: 'sMoney',
              label: '实收金额',
              width: 100
            },
            {
              prop: 'paymentTerm',
              label: '收款方式', width: 120
            },
            {
              prop: 'bankName',
              label: '付款银行名称', width: 120
            },
            {
              prop: 'bankNameCode',
              label: '付款银行账号', width: 120
            },
            {
              prop: 'reamk',
              label: '备注'
            }
          ],
      // 标题
      textMap: {
        edit: '销售收款',
        add: '销售收款'
      },

      // 表单数据（无需赋值，由混入对象赋值）
      formField: this.$utils.getFormField(this, {
        payType:'1',
        invoiceAmount: '',
        invoiceType: '',
        paymentAmount: '',
        paymentMethod: '',
        saleOrderCode: '',
        updateControlId: '',
        receivableAmount:null,
        notReceivableAmount:null,
        actualAmount:null
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode]),

      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectData = selection

          this.handleSelectionChange(selection)
        }
      }
    }
  },
  mounted() {
    // console.log(this.dynamicEditRowData)
    this.formField.saleOrderCode = this.dynamicEditRowData.saleOrderCode
    this.formField.saleOrderId = this.dynamicEditRowData.saleOrderId
    this.formField.receivableAmount = this.dynamicEditRowData.receivableAmount
    this.formField.notReceivableAmount = this.dynamicEditRowData.notReceivableAmount
    this.formField.invoiceAmount = this.dynamicEditRowData.receivableAmount
    this.formField.actualAmount = this.dynamicEditRowData.actualAmount
  },
  watch: {
    'formField.payType': {
      deep: true,
      handler: function(newV, oldV) {
        // if(newV === '1'){
          this.tableComponents.forEach(item=>{
            if(item.isShow == null){
            } else {
              item.isShow = !item.isShow 
            }
          })
        // }
        
      }
    }
  },
  methods: {
    openDialog() {
      this.formField.saleOrderCode = this.dynamicEditRowData.saleOrderCode
      this.formField.saleOrderId = this.dynamicEditRowData.saleOrderId
    },
    closeEdit() {
      this.$emit('update:popupsVisible', false)
    },
    // 详情查询
    queryTableaaa() {
      this.$refs['multipleTable'].listLoading = true     
      var queryid = { saleOrderId: this.dataForForm.saleOrderId }
      // // 先读取参数中的传输对象
      const returnObj = {
      // api配置
        apiConfig: orgApis.querySalesOrderDetails,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: queryid
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
        if (response.result === '0') {
          this.$refs['multipleTable'].listLoading = false
          if (response.msg) {
            this.$message({
              message: response.msg,
              type: 'warn',
              uration: 2000
            })
          }
          return
        }
        // 返回json
        Object.assign(this.dynamicFieldsData, response.rows[0].orderDetails)
        this.carConfigCN = this.dynamicFieldsData.carConfigCN
        var arr1 = response.rows[0].orderCollectionDetails
        for (var i = 0; i < arr1; i++) {
          if (!arr1[i].index) {
            arr1[i].index = i
          }
        }
        this.$refs['multipleTable'].list = arr1
        this.$refs['multipleTable'].listLoading = false
        this.tableKey = this.$utils.generateId()
      }).catch(err => {
        console.info(err)
        this.$refs['multipleTable'].listLoading = false
      })
    },

    // 显示二维码
    showCode() {
      var queryid = { saleOrderId: this.dynamicEditRowData.saleOrderId }
      // // 先读取参数中的传输对象
      const returnObj = {
      // api配置
        apiConfig: orgApis.querySalesOrderDetails,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: queryid
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
        if (response.result === '0') {
          this.$refs['multipleTable'].listLoading = false
          if (response.msg) {
            this.$message({
              message: response.msg,
              type: 'warn',
              duration: 2000
            })
          }
          return          
        }
        Object.assign(this.QRcode, response.rows[0].orderDetails)
        // var {saleOrderDCode,saleAmount,partRepairType ,saleQty } = response.rows[0]
        if(this.formField.paymentAmount >response.rows[0].saleAmount){
          this.$message({
              message: '收款金额不得大于应收尾款',
              type: 'warn',
              duration: 2000
          })
          return
        }


        // pos实际收款 实际支付金额
        let saleAmount1=Number(this.formField.receivableAmount)-Number(this.formField.actualAmount)

        // pos备件品种  精品、备件、其他（存在多个品种时用 / 分隔）   
        let partRepairType1=""
        let temp=[]
        for(let i=0;i<response.rows.length;i++){
          if(temp.indexOf(response.rows[i].partRepairTypeCn)===-1){
            temp.push(response.rows[i].partRepairTypeCn)
          }
        }
        partRepairType1=temp.join('/')
        
        // pos数量   所有购买备件数的累加
        let saleQty1=0
        for(let i=0;i<response.rows.length;i++){
          saleQty1+=response.rows[i].saleQty
        }

        var codeData =
          `{
            "body":
              [
                {
                  "saleOrderDCode": "${this.formField.saleOrderCode}",
                  "saleAmount":"${saleAmount1}",                  
                  "partRepairType": "${partRepairType1}",                 
                  "saleQty":"${saleQty1}",
                  "module":"P"
                }
              ]
          }`
          this.showCodediv = true
          this.$nextTick(function() {
            this.$refs.qrcode.innerHTML = ''
            this.qrcode(200, 200, codeData, 'canvas')
          })
        })
    },
    // 关闭二维码
    closeCode() {
      this.showCodediv = false
    },
    qrcode(qWidth, qHeight, qText, qRender) {
      const qrcode = new QRCode('qrcode', {
        width: qWidth,
        height: qHeight,
        text: qText,
        render: qRender
      })
      qrcode._el.title=''
    },
    // 新增/编辑保存按钮
    save() {
      // console.log(this.dynamicEditRowData)
      const that = this
      // 校验主单数据
      this.$utils.validataMoth(this, 'validpage')
      if (!this.valid) return
      if(Number(this.formField.paymentAmount) > Number(this.formField.receivableAmount) ){
        this.$message({
          message:'收款金额不得大于应收尾款',
          type:"warning"
        })
        return
      }
      this.$utils.validataMoth(this, 'validpopup')
      if (this.valid) {
        that.editSave()
      }
    },

    // 编辑保存
    editSave() {  
      const that = this
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: orgApis.salesCollectionOfSparePartsCollectionin,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: that.formField

      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: response.msg /* 保存成功*/,
            type: 'success',
            duration: 1000
          })
          this.closeEdit()
          this.$nextTick(() => {
            this.$parent.queryTable(1)
          })
        } else {
          // 保存失败
          this.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },

    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.dynamicTableButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.promptSpan{
  position: absolute;
  bottom: 26px;
  right: 335px;
  color: #e70020;
}
/deep/#qrcode img {
  margin: 0 auto;
}
</style>

